07. Exercise: Builder
Building a Builder
Remember that "bean" class, UdacisearchClient
, you worked with in previous exercises? That class has a constructor with lots of parameters. Furthermore, it's a mutable class. It's the perfect candidate for the Builder Pattern.
This should be a fairly straightforward procedure — you are going to take the UdacisearchClient
class and make a Builder
class for it. This will provide the following benefits:
UdacisearchClient
will become an immuable type, which means its value does not change after it is created.- The builder class will emulate named parameters. Unlike the large constructor, the builder makes it harder for callers to accidentally mix up the order of the client properties.
Here's how to apply the builder pattern:
- First, make the
UdacisearchClient
constructorprivate
instead ofpublic
. - Next, make all the instance fields
final
and remove all the setter methods, such asUdacisearchClient#setId(int)
. Congratulations,UdacisearchClient
is now an immutable type — but it's no good if we can't instantiate it! Don't forget to delete the default values of the fields. - Give
UdacisearchClient
a static inner class calledBuilder
. Give the builder class a non-final
instance field corresponding to each field ofUdacisearchClient
. - Create setter methods for all the builder's fields. Each method should return a reference to the
Builder
itself (i.e.,this
). - Finally, add a
UdacisearchClient.Builder#build()
method that calls the now-private
UdacisearchClient
constructor. - Try out
UdacisearchClient.Builder
inMain.java
by constructing theclient
variable with the newBuilder
class:javac Main.java java Main
What do you think? Is the Builder
easier to work with than the old UdacisearchClient
constructor?
TODO List
Task Feedback:
Nice work!
Code
If you need a code on the https://github.com/udacity.
export PATH=/data/jdk-15.0.1/bin:$PATH
export JAVA_HOME=/data/jdk-15.0.1/bin